//
//  MHComposeViewModel.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/4/23.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHComposeViewModel.h"
#import "MHCommonGroupViewModel.h"
#import "MHUploadImage.h"
#import "MHDetailLocationViewModel.h"
#import "MHPublishRedPacketCallBack.h"
@implementation MHComposeViewModel
-(void)initialize
{
    [super initialize];
    self.bindSuccess = false;
    @weakify(self);
    self.closeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        [[AXAppDelegate sharedDelegate] clearPublishDatas];
//        [AXAppDelegate sharedDelegate].inUploading = false;
//        [[AXAppDelegate sharedDelegate].txVideoEditer cancelGenerate];
        [self.services dismissViewModelAnimated:YES completion:NULL];
        return [RACSignal empty];
    }];
    self.style = UITableViewStyleGrouped;
    
    [[MHNotificationCenter rac_addObserverForName:MHRedPacketPaySuccessNotification object:nil] subscribeNext:^(id x) {
        @strongify(self);
        if (![AXAppDelegate sharedDelegate].bindSuccess && [AXAppDelegate sharedDelegate].createModel != nil && ![AXAppDelegate sharedDelegate].finishPublish) {
             [AXAppDelegate sharedDelegate].bindSuccess = YES;
            [AXAppDelegate sharedDelegate].finishPublish = true;
            [self.services dissMissAllPresentModelAnimated:YES];
        }
        
    }];
    
    
    if (self.type == MHCirclComposeTypeVideo) {
        MHUploadImage *pic = [MHUploadImage new];
        pic.image = self.videoCoverImage;
        pic.isGif = NO;
        pic.isVideoCover = YES;
        self.selectPhotos = [@[pic] mutableCopy];
    }
    
    MHCommonGroupViewModel *group0 = [MHCommonGroupViewModel groupViewModel];
    MHCommonArrowItemViewModel *locationViewModel = [MHCommonArrowItemViewModel itemViewModelWithTitle:@"所在位置" icon:@"icon_circle_location"];
    locationViewModel.subtitle = @"";
    
    
    MHCommonArrowItemViewModel *redPacketViewModel = [MHCommonArrowItemViewModel itemViewModelWithTitle:@"发红包" icon:@"ic_theme_package_n"];
    redPacketViewModel.subtitle = @"圈内红包";
    if (self.type == MHCirclComposeTypeVideo) {
        if(![AXAppDelegate sharedDelegate].isAuthorizationExpired)
        {
             group0.itemViewModels = @[locationViewModel];
        }else
        {
            group0.itemViewModels = @[locationViewModel,redPacketViewModel];
        }
        
//        group0.itemViewModels = @[locationViewModel,redPacketViewModel];
        
    }else
    {
         group0.itemViewModels = @[locationViewModel];
    }
    self.dataSource = @[group0];
    
    self.publishCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        void(^doNext)(id x) = ^(MHMoment *moment)
        {
            [MHNotificationCenter postNotificationName:MHReloadMomentPageDataNotification object:nil];
            [self.services dismissViewModelAnimated:YES completion:nil];
            IMAMsg *msg = [IMAMsg msgWithCustom:EIMAMSG_Custom param:[moment yy_modelToJSONString]];
            [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_SendMsgNotification object:msg];
        };
        
        
        if (self.type == MHCirclComposeTypeVideo) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [AXAppDelegate sharedDelegate].publushCircleInfo = self.model;
                [AXAppDelegate sharedDelegate].createModel = self.redPacketCreateModel;
                [AXAppDelegate sharedDelegate].videoContent = self.content;
                
                [AXAppDelegate sharedDelegate].uploadProgress = 0.001;
                [AXAppDelegate sharedDelegate].locationDataString = [self.circleLocation yy_modelToJSONString];
                
                
                if (!self.redPacketCreateModel) {
                    [MBProgressHUD mh_showTips:@"提交视频成功"];
                    [AXAppDelegate sharedDelegate].finishPublish = true;
                    [self.services dissMissAllPresentModelAnimated:YES];
                }else
                {
                    [[[[MHHTTPService sharedInstance] publishRedPacketWithCircleId:self.model.autoId content:[AXAppDelegate sharedDelegate].videoContent locationData:[AXAppDelegate sharedDelegate].locationDataString redData:[self.redPacketCreateModel yy_modelToJSONString] pay:self.redPacketCreateModel.payType] mh_parsedResults] subscribeNext:^(MHPublishRedPacketCallBack *callBack) {
                        @strongify(self);
                         [AXAppDelegate sharedDelegate].callBack = callBack;
                        if (self.redPacketCreateModel.payType != MHCircleComposePayTypeWX) {
                            if (![AXAppDelegate sharedDelegate].bindSuccess && [AXAppDelegate sharedDelegate].createModel != nil && ![AXAppDelegate sharedDelegate].finishPublish)
                            {
                                [AXAppDelegate sharedDelegate].bindSuccess = YES;
                                [AXAppDelegate sharedDelegate].finishPublish = true;
                                [self.services dissMissAllPresentModelAnimated:YES];
                            }
                        }else
                        {
                            [OpenShare OpenUrlLink:callBack.urlScheme Success:^(NSDictionary *message) {
                                [self.services dissMissAllPresentModelAnimated:YES];
                            } Fail:^(NSDictionary *message, NSError *error) {
                                [[AXAppDelegate sharedDelegate] clearPublishDatas];
                            }];
                        }
                       
                    }];
                    
                    

                }
         
            });
            return [RACSignal empty];
        }else
        {
            int askUid = 0;
            //匿名-2
            
            askUid = self.isAnonyMity? - 2 : (self.member?self.member.userId:0);
            return [[[self.services.client publishRecentStoryWithCircleId:self.model.autoId content:self.content data:[input isKindOfClass:[NSArray class]] ? [input yy_modelToJSONString] : nil labels:nil recentType:self.type?2:1 askedUid:askUid vedioData:nil locationData:[self.circleLocation yy_modelToJSONString]] mh_parsedResults] doNext:doNext];
        }
        
    }];
//    self.addUserTagCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
//        return [self.services.client addUserCircleTag:self.model.autoId tagName:input];
//    }];
//
//    self.removeUserTagCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSNumber *number) {
//        int tagId = [number integerValue];
//        return [self.services.client deleteUserCircleTagWithTagId:tagId];
//    }];
    
    
    self.uploadCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSArray *imageArr) {
        @strongify(self);
        [MHHTTPService sharedInstance].swithUrlWithUpload = true;
        NSArray *signals = [[imageArr.rac_sequence  map:^id(MHUploadImage  *image) {
            //            NSData* pictureData = UIImagePNGRepresentation(image);
            if (image.isGif) {
                //                NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
                return [self.services.client uploadDynamicImg:nil fileDatas:@[image.orginalData] miniType:@"image/gif"];;
            }else
            {
                NSData *imageData = UIImageJPEGRepresentation(image.image, 0.5);
                return [self.services.client uploadDynamicImg:nil fileDatas:@[imageData] miniType:nil];;
            }
            
            
        }] array];
        
        NSMutableArray *uploadIamgeArray = [NSMutableArray array];
        
        [MBProgressHUD mh_showProgressHUD:@"上传中..."];
        [[RACSignal concat:signals] subscribeNext:^(NSArray *picArray) {
            [uploadIamgeArray addObject:[picArray lastObject]];
        } error:^(NSError *error) {
            [MHHTTPService sharedInstance].swithUrlWithUpload = false;
            [MBProgressHUD mh_hideHUD];
        } completed:^{
            [MHHTTPService sharedInstance].swithUrlWithUpload = false;
            [self.publishCommand execute:uploadIamgeArray];
            [MBProgressHUD mh_hideHUD];
        }];
        return [RACSignal empty];
    }];
}


- (NSString *)contentTypeWithImageData: (NSData *)data {
    
    uint8_t c;
    
    [data getBytes:&c length:1];
    
    switch (c) {
            
        case 0xFF:
            
            return @"jpeg";
            
        case 0x89:
            
            return @"png";
            
        case 0x47:
            
            return @"gif";
            
        case 0x49:
            
        case 0x4D:
            
            return @"tiff";
            
        case 0x52:
            
            if ([data length] < 12) {
                
                return nil;
                
            }
            
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                
                return @"webp";
                
            }
            
            return nil;
            
    }
    
    return nil;
}


- (instancetype)initWithServices:(id<MHViewModelServices>)services params:(NSDictionary *)params{
    if (self = [super initWithServices:services params:params]) {
        self.model = params[MHViewModelUtilKey];
        self.type = [params[@"MHCirclComposeType"] intValue];
        self.result = params[@"MHComposePublishResult"];
        self.videoCoverImage = params[@"MHCoverImage"];
        self.selectPhotos =  params[@"MHViewModelPhotoes"];
        self.selectAsserts =  params[@"MHViewModelAsserts"];
    }
    return self;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}
@end
